package com.example.administrator.u17.fragment;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.administrator.u17.R;
import com.example.administrator.u17.adapter.FirstFragmentViewPageAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/11/14.
 */

public class FirstFragment extends Fragment implements TabLayout.OnTabSelectedListener {
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private List<Fragment> list;
    private String[] titles;
    private FirstFragmentViewPageAdapter adapter;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = View.inflate(getActivity(), R.layout.fragment_first, null);
        initView(view);
        initData();
        setData();
        setListener();
        return view;
    }

    private void setData() {
        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);
        tabLayout.setTabTextColors(Color.GRAY, Color.rgb(56, 178, 89));
        tabLayout.setSelectedTabIndicatorColor(Color.GREEN);
        tabLayout.setSelectedTabIndicatorHeight(8);

    }

    private void setListener() {
        tabLayout.addOnTabSelectedListener(this);
    }

    private void initData() {
        list = new ArrayList<>();
        list.add(new TuiJianFragment());
        list.add(new VIPFragment());
        list.add(new DingYueFragmnet());
        list.add(new PaiHangFragment());
        titles = getActivity().getResources().getStringArray(R.array.fragment_first_tabLayout);
        adapter = new FirstFragmentViewPageAdapter(getActivity().getSupportFragmentManager(), list, titles);
    }

    private void initView(View view) {
        tabLayout = (TabLayout) view.findViewById(R.id.tabLayout_fragment_first);
        viewPager = (ViewPager) view.findViewById(R.id.vp_fragment_first);
    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        for (int i = 0; i < tabLayout.getTabCount(); i++) {
            if (tabLayout.getTabAt(i) == tab) {
                FragmentTransaction transaction = getActivity().
                        getSupportFragmentManager().beginTransaction();
                viewPager.setCurrentItem(i);
                transaction.addToBackStack(null);
                transaction.commit();
                break;
            }
        }
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }

}
